<!-- 资源共享 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; ">
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane key="查询海关信息" label="查询海关信息" name="查询海关信息" lazy>
          <el-col :xs="24" :sm="24" :lg="24"> 
            <connsearch ref="connsearch" :formOptions="formOptions1"   @search="search" @reset="reset1" @viewEncoding="viewEncoding" @dataSelection="dataSelection" :HS="true"/>
            <el-table stripe border :data="tableData1" style="width: 100%; margin-top: 15px" height="520">
              <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
              <el-table-column label="供应商" prop="Supplier" align="left" width="200">
                <template slot-scope="{row}">
                  <div style="display:flex;align-items:center;">
                    <el-tooltip class="item" effect="dark" :content="row.Supplier === '' ? '无法查看公司名' : row.Supplier" placement="top">
                      <span class="Supplier">{{ row.Supplier === '' ? '无法查看公司名' : row.Supplier}}</span>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="AI决策人" placement="top">
                      <el-button style="margin-left:10px;" v-show="row.Supplier" icon="el-icon-user-solid" circle size="mini" type="primary" @click="replyDetails(row.Supplier)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="采购商" prop="Purchaser" align="left" width="200">
                <template slot-scope="{row}">
                  <div style="display:flex;align-items:center;">
                    <el-tooltip class="item" effect="dark" :content="row.Purchaser === '' ? '无法查看公司名' : row.Purchaser" placement="top">
                      <span class="Purchaser">{{ row.Purchaser === '' ? '无法查看公司名' : row.Purchaser }}</span>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="AI决策人" placement="top">
                      <el-button style="margin-left:10px;" v-show="row.Purchaser" icon="el-icon-s-custom" circle size="mini" type="primary" @click="replyDetails(row.Purchaser)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="货运介绍" prop="FreightIntro" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="出口国/地区" prop="OutCountry" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="起运港" prop="OutPort" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="进口国/地区" prop="InCountry" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="目的港" prop="InPort" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="日期" prop="Date" align="left" show-overflow-tooltip></el-table-column>
            </el-table>
            <el-pagination 
              @current-change="handleCurrentChange1" 
              :current-page=pageNum1
              background 
              layout="total, prev, pager, next, jumper"
              :page-count="total1">
            </el-pagination>
          </el-col>
        </el-tab-pane>
        <el-tab-pane key="查询公司决策人" label="查询公司决策人" name="查询公司决策人" lazy>
          <el-col :xs="24" :sm="24" :lg="24"> 
            <connsearch ref="connsearch" :formOptions="formOptions2"   @search="search" @reset="reset2"/>
            <el-table stripe border :data="tableData2" style="width: 100%; margin-top: 15px" height="520">
              <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
              <el-table-column label="名称" prop="Name" width="200" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="公司名/职位" prop="CompanyName" align="left" show-overflow-tooltip>
                <template slot-scope="{row}">
                  {{ row.CompanyName }} / {{ row.Position }}
                </template>
              </el-table-column>
              <el-table-column label="邮箱" prop="Email" align="left" width="600" show-overflow-tooltip>
                <template slot-scope="{row}">
                  <div style="display:flex;align-items:center;">
                    <el-tooltip class="item" effect="dark" :content="row.Email === '' ? '非正式用户，信息隐藏' : row.Email" placement="top">
                      <span class="Purchaser" style="width:500px;">{{ row.Email === '' ? '非正式用户，信息隐藏' : row.Email }}</span>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="加入群发" placement="top">
                      <el-button style="margin-left:10px;" v-show="row.Email" icon="el-icon-message" circle size="mini" type="primary" @click="sendEmail(row)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination 
              @current-change="handleCurrentChange2" 
              :current-page=pageNum2
              background 
              layout="total, prev, pager, next, jumper"
              :page-count="total2">
            </el-pagination>
          </el-col>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      top="5vh"
      title="商品国家选择"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="90%">
      <div style="display: flex;">
        <div>
          <div style="color:#2491fc;"><span style="display:inline-block;width:15px;height:15px;background:#2491fc;border-radius:50%;margin-right:5px;margin-bottom:-3px;"></span>商品供应国家</div>
          <div style="display:flex;flex-wrap:wrap;width:100%;">
            <div v-for="(item, index) in CountrysList" :key="index" style="width:130px;height:40px;display:flex;align-items:center;margin-right:5px;cursor: pointer;" @click="outCountryClick(item.Country)">
              <span v-show="!outCountry.includes(item.Country)" style="display:inline-block;width:15px;height:15px;background:#ccc;border-radius:50%;margin-right:5px;flex-shrink: 0;"></span>
              <span v-show="outCountry.includes(item.Country)" class="el-icon-success" style="margin-right:5px;flex-shrink: 0;color:#2491fc;font-size:16px;"></span>
              <el-image :src="item.flag" style="height:15px;margin:0 5px;"></el-image>
              <div style="font-size:13px;">{{ item.Country }}</div>
            </div>
          </div>
        </div>
        <div style="width: 1px;background:#ddd;margin-right:50px"></div>
        <div>
          <div style="color:#2491fc;"><span style="display:inline-block;width:15px;height:15px;background:#2491fc;border-radius:50%;margin-right:5px;margin-bottom:-3px;"></span>商品采购国家</div>
          <div style="display:flex;flex-wrap:wrap;width:100%;">
            <div v-for="(item, index) in CountrysList" :key="index" style="width:130px;height:40px;display:flex;align-items:center;margin-right:5px;cursor: pointer;" @click="inCountryClick(item.Country)">
              <span v-show="!inCountry.includes(item.Country)" style="display:inline-block;width:15px;height:15px;background:#ccc;border-radius:50%;margin-right:5px;flex-shrink: 0;"></span>
              <span v-show="inCountry.includes(item.Country)" class="el-icon-success" style="margin-right:5px;flex-shrink: 0;color:#2491fc;font-size:16px;"></span>
              <el-image :src="item.flag" style="height:15px;margin:0 5px;"></el-image>
              <div style="font-size:13px;">{{ item.Country }}</div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="海关编码"
      :visible.sync="codingDialog"
      v-el-drag-dialog
      width="80%">
      <el-tree
        accordion
        :data="HSCodeList"
        node-key="HsCode"
        @node-click="checkChange"
        :props="{ label:'Name', value:'HsCode', children: 'Child', expandTrigger: 'hover' }">
        <template slot-scope="{node, data}">
          <el-tooltip effect="dark" :content="data.tooltip" placement="top-start" style="font-size:14px;">
          <span>{{node.label}}<span v-if="data.HsCode">  (品目编码：{{ data.HsCode}})</span></span>
          </el-tooltip>
        </template>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="codingDialog = false;">关 闭</el-button>
        <!-- <el-button type="primary" @click="submitCode()">确认</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest, customsrequest } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import connsearch from "@/components/connSearch";
export default {
  components: { connsearch },
  directives: { elDragDialog },
  data() {
    let that = this
    return {
      pageNum1: 1,
      pageSize1: 10,
      pageNum2: 1,
      pageSize2: 10,
      dialogVisible: false,
      codingDialog: false,
      outCountry: [],
      HSCodeList: [],
      inCountry: [],
      label: '查询海关信息',
      activeName: '查询海关信息',
      searchform1: {},
      searchform2: {},
      tableData1: [],
      total1: 0,
      tableData2: [],
      total2: 0,
      CountrysList: [],
      tablist: [
        '查询海关信息', '查询公司决策人'
      ],
      formOptions1: [
        {
          label: "HS编码",
          prop: "Hscode",
          element: "el-input",
          placeholder: "请输入HS编码",
          events: {
            input(val) {
              that.searchform1.Hscode = val
            },
          },
        },
        {
          label: "商品名称",
          prop: "ProductName",
          element: "el-input",
          placeholder: "请输入商品名称",
          events: {
            input(val) {
              that.searchform1.ProductName = val
            },
          },
        },
        {
          col: 6,
          label: "开始日期",
          prop: "StartDate",
          element: "el-date-picker2",
          initValue: '',
          type: "date",
          events: {
            input(val) {
              that.searchform1.StartDate = val
            },
          },
        },
        {
          col: 6,
          label: "结束日期",
          prop: "EndDate",
          element: "el-date-picker2",
          initValue: '',
          type: "date",
          events: {
            input(val) {
              that.searchform1.EndDate = val
            },
          },
        },
      ],
      formOptions2: [
        {
          col: 8,
          label: "公司名",
          prop: "Keyword",
          initValue: '',
          element: "el-input",
          placeholder: "请输入公司名",
          events: {
            input(val) {
              that.searchform2.Keyword = val
            },
          },
        },
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDetailFileContent()
    this.receiveInformation()
    this.activeName = this.$route?.query?.activeName ? this.$route?.query?.activeName : '查询海关信息'
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    if(this.$route?.query?.Keyword){
      const encodedParam = decodeURIComponent(this.$route?.query?.Keyword)
      this.formOptions2.map( item => {
        if(item.label === '公司名'){
          item.initValue = encodedParam
        }
      })
      this.label = this.$route?.query?.activeName
      this.searchform2.Keyword = encodedParam
      this.$refs.connsearch.addInitValue()
      this.search()
    }
  },
  methods: {
    async sendEmail(row){
      let ToAccounts = []
      row.Email.split(',').map(item => {
        ToAccounts.push( { CorpName: row.CompanyName, UserName: row.Name, EMail:item } )
      })
      const data = {
        Data:{
          TaskName: '手工添加海关邮箱',
          ToAccounts
        }
      }
      const res = await connrequest('ImportEMailADTask', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('加入群发成功')
      }
    },
    checkChange(){},
    async receiveInformation(){
      const HSCode = await connrequest('GetHSCode')
      this.HSCodeList = this.setTooltip(HSCode.Data)
    },
    setTooltip(treeData){
      treeData.forEach(node => {
        if (node.HsCode) {
          node.tooltip = `${node.Name} (品目编码：${node.HsCode})`;
        } else {
          node.tooltip = node.Name;
        }
        if (node.Child) {
          this.setTooltip(node.Child);
        }
      })
      return treeData
    },
    outCountryClick(country){
      if (this.outCountry.length < 3 && !this.outCountry.includes(country)) {
        this.outCountry.push(country);
      } else if (this.outCountry.includes(country)) {
        let index = this.outCountry.indexOf(country);
        this.outCountry.splice(index, 1);
      } else {
        this.$message.info('请选中不超过三个国家');
      }
    },
    inCountryClick(country){
      if (this.inCountry.length < 3 && !this.inCountry.includes(country)) {
        this.inCountry.push(country);
      } else if (this.inCountry.includes(country)) {
        let index = this.inCountry.indexOf(country);
        this.inCountry.splice(index, 1);
      } else {
        this.$message.info('请选中不超过三个国家');
      }
    },
    replyDetails(name){
      this.activeName = '查询公司决策人'
      this.formOptions2.map( item => {
        if(item.label === '公司名'){
          item.initValue = name
        }
      })
      this.label = '查询公司决策人'
      this.$set(this.searchform2, 'Keyword', name)
      this.$refs.connsearch.addInitValue()
      this.search()
      // window.open(`${process.env.VUE_APP_BASE_API}/#/resource/emailInformation?activeName=查询公司决策人&&Keyword=${encodedParam}`);
    },
    async GetDetailFileContent(){
      const data = {
        Data:{
          FileName: '/school/config/national_flag_img.json'
        }
      }
      const res = await connrequest('GetDetailFileContent', data)
      let array = JSON.parse(res.Data.Content);
      const CountrysList = Object.entries(array).map(([country, flag]) => ({ Country: country, flag: `${process.env.VUE_APP_BASE_API}/national_flag_img/${flag}` }));
      this.CountrysList = CountrysList
      this.formOptions1.map( item => {
        if(item.label === '商品供应国家' || item.label === '商品采购国家' ){
          item.options = CountrysList
        }
      })
    },
    viewEncoding(){
      this.codingDialog = true
    },
    dataSelection(){
      this.dialogVisible = true
    },
    async handleClick(row){
      this.label = row.label
    },
    async search(){
      if(this.label === '查询海关信息'){
        if(!this.searchform1.Hscode && !this.searchform1.ProductName){
          this.$message.error('请输入海关编码或商品名称')
          return
        }
        let StartDate = new Date(this.searchform1.StartDate);
        let EndDate = new Date(this.searchform1.EndDate);
        if ((this.searchform1.StartDate && this.searchform1.EndDate) && StartDate > EndDate) {
            this.$message.error('开始日期不能大于结束日期！')
            return
        }
        this.pageNum1 = 1
        const data = {
          Data: {
            PageNum: this.pageNum1,
            ...this.searchform1,
            inCountry: this.inCountry.join(),
            outCountry: this.outCountry.join()
          }
        }
        const res = await customsrequest('cust', data)
        this.tableData1 = res.Data.Result
        this.total1 = res.Data.TotalPage
      }else if(this.label === '查询公司决策人'){
        if(!this.searchform2.Keyword){
          this.$message.error('请输入公司名称')
          return
        }
        this.pageNum2 = 1
        const data = {
          Data: {
            Keyword: this.searchform2.Keyword,
            PageNum: this.pageNum2,
          }
        }
        const res = await customsrequest('decmak', data)
        res.Data.Result.map(item => {
          if(item.Email.length > 0){
            item.Email = item.Email.join(',')
          }else{
            item.Email = ''
          }
          return item
        })
        this.tableData2 = res.Data.Result
        this.total2 = res.Data.TotalPage
      }
    },
    reset1(){
      this.PageNum1 = 1
      this.formOptions1 = this.formOptions1.map( item => {
        item.initValue = ""
        return item
      })
      this.inCountry = []
      this.outCountry = []
      this.searchform1 = {}
      this.$refs.connsearch.addInitValue()
    },
    reset2(){
      this.PageNum2 = 1
      this.formOptions2 = this.formOptions2.map( item => {
        item.initValue = ""
        return item
      })
      this.searchform2 = {}
      this.$refs.connsearch.addInitValue()
    },
    async handleCurrentChange1(val){
      if(!this.searchform1.Hscode && !this.searchform1.ProductName){
        this.$message.error('请输入海关编码或商品名称')
        return
      }
      let StartDate = new Date(this.searchform1.StartDate);
      let EndDate = new Date(this.searchform1.EndDate);
      if ((this.searchform1.StartDate && this.searchform1.EndDate) && StartDate > EndDate) {
        this.$message.error('开始日期不能大于结束日期！')
        return
      }
      this.pageNum1 = val
      const data = {
          Data: {
            PageNum: this.pageNum1,
            ...this.searchform1
          }
        }
        const res = await customsrequest('cust', data)
        this.tableData1 = res.Data.Result
        this.total1 = res.Data.TotalPage
    },
    async handleCurrentChange2(val){
      if(!this.searchform2.Keyword){
        this.$message.error('请输入公司名称')
        return
      }
      this.pageNum2 = val
      const data = {
          Data: {
            Keyword: this.searchform2.Keyword,
            PageNum: this.pageNum2,
          }
        }
        const res = await customsrequest('decmak', data)
        res.Data.Result.map(item => {
          if(item.Email.length > 0){
            item.Email = item.Email.join(',')
          }else{
            item.Email = ''
          }
          return item
        })
        this.tableData2 = res.Data.Result
        this.total2 = res.Data.TotalPage
    },
  }
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.Supplier,.Purchaser{
  width: 100%;
  display: inline-block;
  overflow: hidden; //超出的文本隐藏
  text-overflow: ellipsis; //溢出用省略号显示
  white-space: nowrap; //溢出不换行
}
</style>